#!/bin/bash

function fun_help()
{
    echo -e "zcgrep [options] keystring [path]"
    echo -e "  find keystring in cpp, c, h"
    echo -e "  options:"
    echo -e "     -w force keystring to match only whole words"
    echo -e "     -i ignore case distinctions"
    echo -e "     -v select non-matching lines"
    echo -e "     -s show the run command"
    echo -e "  eg:"
    echo -e "  zcgrep chenming                  find \"chenming\" in current folder"
    echo -e "  zcgrep chenming Supernva         find \"chenming\" in Supernova"
    echo -e "  zcgrep -w chenming  Supernova    find \"chenming\" in Supernova match only whole words and case distinctions"
    echo -e "  zcgrep -w -i chenming  Supernova find \"chenming\" in Supernova match only whole words and ignore case distinctions"
}

OPT_W=""
OPT_I=""
# show color
OPT_C="--color"
OPT_EN_SHOW=FALSE

while getopts :iwvsh OPT
do
   case $OPT in
        w)  OPT_W="-w";;
        s)  OPT_EN_SHOW="TRUE";;
	    i)  OPT_I="-i";;
        h)
            fun_help
            exit 0
            ;;
        ?)
            echo -en "\033[31;40;1m"
            echo -e  "format error!!!"
            fun_help
            echo -e "\033[0m"
            exit 1;;
    esac
done

## fisrt para  --> keystring
## second pare --> path
LOCAL_KEYSTR=""
LOCAL_PATH="."
idx=1
while [ $idx -le $# ]
do
    # echo ${!idx}
    item="${!idx}"

    if [ ${item:0:1} != "-" ]; then
        if [ "$LOCAL_KEYSTR"x == ""x ]; then
            LOCAL_KEYSTR=$item
        else
            LOCAL_PATH=$item
            break
        fi
    fi

    let idx+=1
done

if [ "$LOCAL_KEYSTR"x == ""x ]; then
    echo -en "\033[31;40;1m"
    echo -e  "keystring must't empty"
    fun_help
    echo -e "\033[0m"
    exit 1
fi

if test $OPT_EN_SHOW = "TRUE" ; then
    echo -en "\033[32;40;1m"

    echo "ag ${LOCAL_PATH} --cpp --cc -a --color-match '31;40;1' ${OPT_I} ${OPT_W} \"${LOCAL_KEYSTR}\""

    echo -e "\033[0m"
fi
ag --hh -a --color-match '31;40;1' ${OPT_W} ${OPT_I} ${LOCAL_KEYSTR}

